package com.ken.astroboy.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ken.astroboy.dto.AdminDto;
import com.ken.astroboy.dto.WelcomeMsgDto;
import com.ken.astroboy.logic.LogicProcess;
import com.ken.astroboy.result.OperationResult;
import com.ken.astroboy.util.CipherUtils;
import com.ken.astroboy.util.Exceptions;
import com.ken.astroboy.vo.AdminVo;

@Controller
public class AdminController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @RequestMapping("/login")
    public String login(@RequestParam(value = "account", required = false) String account,
                        @RequestParam(value = "password", required = false) String password,
                        HttpServletRequest request) {
        
        logger.debug("Enter /login");
        logger.debug("account:{} password:{}", account, password);

        if(request.getSession().getAttribute("user") != null ){
            return "redirect:panel";
        }else{
            if(StringUtils.isNotBlank(account)){
            	
            	if(account.trim().equals("admin")) {
                    if(password.equals("complexp@ss")) {
                        request.getSession().setAttribute("user", account);
                        return "redirect:panel";	
                    }else {
                    	request.getSession().setAttribute("errorMsg", "密码错误");
                    	return "login";
                    }
            	}
                
                AdminVo entity = LogicProcess.getAdmin(account);
                        
                if(entity != null){
                    
                    if(entity.getStatus() == AdminVo.ENABLED){
                        
                        String plaintext = null;
                        try {
                            plaintext = CipherUtils.decrypt(entity.getPassword());
                        } catch (Exception e) {
                            logger.debug(Exceptions.getExceptionDetail(e));
                            
                            request.getSession().setAttribute("errorMsg", "密码加解密出现错误");
                            return "login";
                        }

                        if(plaintext.equals(password)){
                            request.getSession().setAttribute("user", account);
                            return "redirect:panel";
                        }else{
                            request.getSession().setAttribute("errorMsg", "密码错误");
                        }
                    }else{
                        request.getSession().setAttribute("errorMsg", "此用户已停用");
                    }
                }else{
                    request.getSession().setAttribute("errorMsg", "此用户不存在");
                }
            }
        }
        
        return "login";
    }

    @RequestMapping("/panel")
    public String panel(HttpServletRequest request){
                
        logger.debug("Enter /panel");
 
        logger.debug("user in session: {}", request.getSession().getAttribute("user"));
              
        return "panel";
    }
    
    @RequestMapping("logout")
    public String logout(HttpServletRequest request){
        
        request.getSession().removeAttribute("user");
        request.getSession().removeAttribute("errorMsg");

        return "redirect:login";
    }
    
    @RequestMapping("/admin-list")
    @ResponseBody
    public Object adminList(){
        
        List<AdminVo> list = new ArrayList<>();
        
        list = LogicProcess.getAdminList();
        
        return list;
    }
    
    @RequestMapping("enAdmin/{account}")
    @ResponseBody
    public Object enAdmin(@PathVariable String account) {

        logger.debug("Enter enAdmin/{account}");
        logger.debug("account: {}", account);

        if(LogicProcess.enableAdmin(account)){

            return LogicProcess.getAdminList();

        }else{                       
            return new OperationResult(false, "fail");
        }
    }

    @RequestMapping("disAdmin/{account}")
    @ResponseBody
    public Object disAdmin(@PathVariable String account) {

        logger.debug("Enter disAdmin/{account}");
        logger.debug("account: {}", account);

        if(LogicProcess.disableAdmin(account)){

            return LogicProcess.getAdminList();

        }else{                       
            return new OperationResult(false, "fail");
        }
    } 
    
    @RequestMapping("removeAdmin/{account}")
    @ResponseBody
    public Object removeAdmin(@PathVariable String account) {

        logger.debug("Enter removeAdmin/{account}");
        logger.debug("account: {}", account);

        if(LogicProcess.removeAdmin(account)){

            return LogicProcess.getAdminList();

        }else{                       
            return new OperationResult(false, "fail");
        }
    } 
    
    @RequestMapping(value="createAdmin", method=RequestMethod.POST)
    @ResponseBody
    public Object createAdmin(AdminDto msg, HttpServletRequest request) {

        logger.debug("Enter createAdmin");
        logger.debug("AdminDto: {}", msg.toString());

        OperationResult result = new OperationResult(true, "ok");

        StringBuilder errorReport = new StringBuilder();
        String account = StringUtils.trim(msg.getAccount());
        boolean isCreate = false;

        if(WelcomeMsgDto.CREATE_MODE.equals(msg.getMode())){
            
            isCreate = true;
            
            //Check account
    
            if(StringUtils.isBlank(account)){
                errorReport.append("账号为空\r\n");
            }else if(LogicProcess.getAdmin(account) != null){
                errorReport.append("账号[" + account + "]已存在\r\n");
            }else if(account.equals("admin")) {
            	errorReport.append("账号[" + account + "]是已存在的系统账号\r\n");
            }
        }       
        
        if(errorReport.length() == 0){
          
            AdminVo entity = new AdminVo();

            entity.setAccount(account);
            
            try {
                entity.setPassword(CipherUtils.encrypt(msg.getPassword()));
            } catch (Exception e) {
                logger.info(Exceptions.getExceptionDetail(e));

                result.setStatus(false);
                result.setDescription("密码加密失败"); 
                return result;
            }
            
            if(AdminDto.EDIT_MODE.equals(msg.getMode())){
                
                AdminVo old = LogicProcess.getAdmin(account);
                
                if(old != null){
                    entity.setStatus(old.getStatus());
                }           
            } 
            
            
            if(LogicProcess.createOrModifyAdmin(entity, isCreate)){
                List<AdminVo> list = LogicProcess.getAdminList();
                return list; 
            }else{
                result.setStatus(false);
                result.setDescription("保存失败");  
            }
        }else{    
            result.setStatus(false);
            result.setDescription("输入参数有误：" + errorReport);
        }

        return result;              
    }
  
    @RequestMapping(value="changePassword", method=RequestMethod.POST)
    @ResponseBody
    public Object changePassword(AdminDto msg, HttpServletRequest request) {

        logger.debug("Enter changePassword");
        logger.debug("AdminDto: {}", msg.toString());

        OperationResult result = new OperationResult(true, "密码修改成功");      

        AdminVo entity = new AdminVo();

        entity.setAccount(msg.getAccount());

        try {
            entity.setPassword(CipherUtils.encrypt(msg.getPassword()));
        } catch (Exception e) {
            logger.info(Exceptions.getExceptionDetail(e));

            result.setStatus(false);
            result.setDescription("密码加密失败"); 
            return result;
        }

        entity.setStatus(AdminVo.ENABLED);

        if(!LogicProcess.createOrModifyAdmin(entity, false)){
            result.setStatus(false);
            result.setDescription("保存失败");  
        }

        return result;              
    }
  
    
    @RequestMapping("/read-log")
    @ResponseBody
    public Object systemLog(){
                
        return LogicProcess.getSystemLog();
        
    }
}
